package natappvip.liujinliang.db;

import java.sql.Connection;
import java.sql.SQLException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import natappvip.liujinliang.exception.JdbcException;

/**
 * @ClassName:  ConnectionManager   
 * @Despt: 数据库连接类  
 * @Auth: Liujinliang 
 * @Date: 2018年7月29日 下午9:39:27
 */
public class ConnectionManager {
	
	private static Logger logger = LoggerFactory.getLogger(ConnectionManager.class);
	
	private static DbConnectionPool pool = null;
	
	/*
	 * 每个线程的Connection都由ThreadLocal来维护，ThreadLocal就是用来维护线程自己本身的变量的
	 */
	private final static ThreadLocal<Connection> conns = new ThreadLocal<Connection>();
	
	static {
		pool = new DbConnectionPool();
	}
	
	public static Connection getConnection() {
		Connection conn = conns.get();
		try {
			if(conn ==null || conn.isClosed()){
				conn = pool.getConnection();	// 从线程池获取连接
				conn.setAutoCommit(false);		// 默认设置开启事务
				conns.set(conn);				// 由线程自身来维护 
			}
		} catch (SQLException e) {
			logger.info("获取连接失败");
			throw new JdbcException(e.getMessage());
		}
		return conn;
	}
	
	public static void commitTransaction() {
		Connection conn = conns.get();
		if (conn != null) {
			try {
				conn.commit();
			} catch (SQLException e) {
				logger.info("{}连接提交失败", conn);
				throw new JdbcException(e.getMessage());
			}
		} 
		else {
			logger.info("{}连接提交失败，当前连接为空", conn);
		}
	}
	
	public static void rollbackTransaction() {
		Connection conn = conns.get();
		if (conn != null) {
			try {
				conn.rollback();
			} catch (SQLException e) {
				logger.info("{}连接提交失败", conn);
				throw new JdbcException(e.getMessage());
			}
		}
		else {
			logger.info("{}连接回滚失败，当前连接为空", conn);
		}
	}
	
	public static void closeConnection() {
		Connection conn = conns.get();
		if (conn != null) {
			pool.freeConnection(conn);
		}
		conns.set(null);
	}
	
	public void emptyPool() {
		pool.emptyPool();
	}
	
	@Override
	protected void finalize() throws Throwable {
		emptyPool();
		super.finalize();
		System.gc();
	}
}
